package com.sun;

import java.util.*;
import java.util.stream.Collectors;

/**
 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 * 给定一个字符串 s ，请你找出其中不含有重复字符的 最长子串 的长度。
 */
public class Test3LengthOfLongestSubstring {
    public static void main(String[] args) {
        String str = "abcadac";
        int i = lengthOfLongestSubstring1(str);
        System.out.println(i);

    }

    /**
     *暴力求解法
     */
    public static int lengthOfLongestSubstring(String str){
        int max = 0;
        for (int i = 0; i < str.length(); i++) {
            for (int j = i+1; j <= str.length(); j++) {
                String string = str.substring(i,j);
                Set<String> stringSet = new HashSet<>();
                for (int k = 0; k < string.length(); k++) {
                    stringSet.add(string.substring(k,k+1));
                }
                if(stringSet.size()==string.length()){
                    max = Math.max(max,string.length());
                }
            }
        }
        return max;
    }
    /**
     * 滑动窗口
     */
    public static int lengthOfLongestSubstring1(String str){
        int max = 0, start = 0;
        HashMap<Character, Integer> hashMap = new HashMap<>();
        for (int end = 0; end < str.length(); end++){
            char character = str.charAt(end);
            if(hashMap.containsKey(character)){
                start = Math.max(start,hashMap.get(character));
            }
            max = Math.max(max,end - start);
            hashMap.put(character,end);
        }
        return max;
    }


}
